import sys
from typing import Dict, List

from config import config
from request import get_req
from database import DB


def get_document(doc_no):
    url = f"https://open.feishu.cn/open-apis/doc/v2/{doc_no}/content/"
    headers = {
        "Authorization": "Bearer " + config.tenant_access_token(),
        "Content-Type": "application/json; charset=utf-8"
    }
    rsp_dict = get_req(url, headers)
    if rsp_dict["code"] == 0:
        with open("json_templates/temp.json", "w") as file_out:
            file_out.write(rsp_dict["data"]["content"])
    else:
        print("Error!", rsp_dict["msg"])


def get_depart_list():
    url = "https://open.feishu.cn/open-apis/contact/v3/departments"
    headers = {
        "Authorization": "Bearer " + config.tenant_access_token(),
    }
    rsp_dict = get_req(url, headers, parm={"page_size": 50, "fetch_child":True, "department_id_type":"department_id", "parent_department_id":0})
    if rsp_dict["code"] == 0:
        return rsp_dict["data"]["items"]
    else:
        print("Error! ", rsp_dict["msg"])
        return []


def get_user_list(department_id=None) -> List[Dict]:
    url = "https://open.feishu.cn/open-apis/contact/v3/users/"
    headers = {
        "Authorization": "Bearer " + config.tenant_access_token(),
    }
    parm = {"page_size": 50}
    if not department_id is None:
        parm["department_id_type"] = "department_id"
        parm["department_id"] = department_id
    rsp_dict = get_req(url, headers, parm)
    if rsp_dict["code"] == 0:
        return rsp_dict["data"]["items"]
    else:
        print("Error! ", rsp_dict["msg"])
        return []


def create_users(ip):
    db = DB(ip)
    departs = get_depart_list()+[{"department_id": '0'}]
    for de in departs:
        data = get_user_list(de["department_id"])
        for user in data:
            if db.user.find_one({"openId":user["open_id"]}) is None:
                db.user.insert_one({
                    "userName": user["name"],
                    "openId": user["open_id"],
                    "userId": user["user_id"],
                    "departmentId": user["department_ids"][0]
                })
                print(user["name"])
        

if __name__ == "__main__":
    if len(sys.argv) > 2 and sys.argv[1] == "get":
        get_document(sys.argv[2])
    elif len(sys.argv) > 2 and sys.argv[1] == "create_users":
        create_users(sys.argv[2])
    else:
        create_users('localhost')
